package com.xstudio.pvzreborn.entity.entities.misc;

import com.xstudio.pvzreborn.entity.entities.PVZEntityBase;
import com.xstudio.pvzreborn.utils.CapabilityUtils;
import com.xstudio.pvzreborn.utils.TickUnit;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;

/**
 * @author <a href="https://gitee.com/Bread_NiceCat">Bread_NiceCat</a>
 * @date 2023/1/17 16:03
 */
public class EntitySunshine extends PVZEntityBase {
	public static final String NAME = "sunshine";
	public static final String SUNSHINE_TAG = "sunshine", MAX_AGE_TAG = "max_age";
	private static final EntityDataAccessor<Integer> SUNSHINE_DATA = SynchedEntityData.defineId(EntitySunshine.class, EntityDataSerializers.INT);
	private static final EntityDataAccessor<Integer> MAX_AGE_DATA = SynchedEntityData.defineId(EntitySunshine.class, EntityDataSerializers.INT);
	//==RendererVars==
	public static final int whenStartFlickering = TickUnit.toTick(9f);
	public int renderCounter = 0;

	public EntitySunshine(EntityType<?> pEntityType, Level pLevel) {
		super(pEntityType, pLevel);
	}

	public int getSunshine() {
		return entityData.get(SUNSHINE_DATA);
	}

	public void setSunshine(int sunshine) {
		entityData.set(SUNSHINE_DATA, sunshine);
	}

	public Integer getMaxAge() {
		return entityData.get(MAX_AGE_DATA);
	}

	@Override
	protected void defineSynchedData() {
		entityData.define(SUNSHINE_DATA, 0);
		entityData.define(MAX_AGE_DATA, TickUnit.toTick(15f));
	}

	@Override
	public void tick() {
		super.tick();
		if (tickCount >= getMaxAge()) {
			kill();
		}
	}

	@Override
	public void playerTouch(@NotNull Player pPlayer) {
		kill();
		if (pPlayer instanceof ServerPlayer sp) {
			CapabilityUtils.getSunshine(pPlayer).ifPresent((sun) -> sun.add(getSunshine(), sp));
		}
	}

	@Override
	protected void readAdditionalSaveData(@NotNull CompoundTag pCompound) {
		setSunshine(pCompound.getInt(SUNSHINE_TAG));
		if (pCompound.contains(MAX_AGE_TAG)) {
			entityData.set(MAX_AGE_DATA, pCompound.getInt(MAX_AGE_TAG));
		}
	}

	@Override
	protected void addAdditionalSaveData(@NotNull CompoundTag pCompound) {
		pCompound.putInt(SUNSHINE_TAG, getSunshine());
		pCompound.putInt(MAX_AGE_TAG, getMaxAge());
	}

}
